package com.ten.mall.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.ten.mall.service.DoctorService;
import com.ten.mall.service.MessageService;
import com.ten.mall.service.UserService;
import com.ten.mall.utils.CommonUtis;
import com.ten.mall.utils.HttpClientUtil;
import com.ten.mall.utils.MessageUtil;
import com.ten.mall.utils.WeiXinUtils;
import com.ten.mall.vo.Doctor;
import com.ten.mall.vo.MyMessage;
import com.ten.mall.vo.User;
import com.ten.mall.vo.weixin.AccessToken;
import com.ten.mall.vo.weixin.UnicodeResult;
import com.ten.mall.vo.weixin.UserInfo;
import com.ten.mall.vo.weixin.WebAuthorToken;

@Controller
public class WeiXinController {
	@Value("${weixin_token}")
	private String token;
	@Value("${app_secret}")
	private String appSecret;
	@Value("${weixin_appid}")
	private String appId;
	@Value("${mch_id}")
	private String mchId;
	@Value("${key}")
	private String key;
	@Value("${server_name}")
	private String server_name;
	@Autowired
	private UserService userService;
	@Autowired
	private DoctorService doctorService;
	@Autowired
	private MessageService messageService;
	
	private Logger log = LoggerFactory.getLogger(WeiXinController.class);
	@RequestMapping(value = "/weixin", method = RequestMethod.GET)
	@ResponseBody
	public String doCheck(HttpServletRequest req) {
		log.info("get方法" + "get");
		String signature = req.getParameter("signature");
		String timestamp = req.getParameter("timestamp");
		String nonce = req.getParameter("nonce");
		String echostr = req.getParameter("echostr");
		boolean b = CommonUtis.chechSignature(signature, timestamp, nonce, token);
		if (b) {
			return echostr;
		} else {

			return "";
		}
	}

	@RequestMapping(value = "/weixin", method = RequestMethod.POST, produces = "application/xml;charset=utf-8")
	@ResponseBody
	private String checkWeixinPost(HttpServletRequest request) throws Exception {
		String message = "";
		String dir=server_name+"/phone/test";
		String tir =server_name+"/phone/center";
		String accessToken="";
		String doctorUrl =WeiXinUtils.createMyEncodeUrl(appId,dir);
		String shopUrl=WeiXinUtils.createMyEncodeUrl(appId,tir);
		Map<String, String> map = MessageUtil.xmlToMap(request);
		if (MessageUtil.MESSAGE_EVNET.equals(map.get("MsgType"))) {
			String eventType = map.get("Event");
			String eventKey = map.get("EventKey");
			if (MessageUtil.MESSAGE_SUBSCRIBE.equals(eventType)) {
				AccessToken access=userService.selectToken();
				if(access==null||StringUtils.isBlank(access.getAccessToken())){
					String res =HttpClientUtil.getAccessToken(appId, appSecret);
					log.info("res:"+res);
					if(res.indexOf("error") < 0){
						AccessToken token =JSON.parseObject(res, AccessToken.class);
						token.setCreateTime(new Date());
						userService.insertToken(token);
						accessToken =token.getAccessToken();
					}
				}else if(CommonUtis.isDisable(access)){
					String res =HttpClientUtil.getAccessToken(appId, appSecret);
					if(res.indexOf("error") < 0){
						AccessToken token =JSON.parseObject(res, AccessToken.class);
						token.setCreateTime(new Date());
						token.setId(access.getId());
						userService.updateToken(token);
						accessToken =token.getAccessToken();
					}
				}else{
					accessToken =access.getAccessToken();
				}
				String ss = WeiXinUtils.getUserInfo(accessToken, map.get("FromUserName"), "zh_CN");
				log.info("ss:"+ss);
				UserInfo info=null;
				User u =null;
				if (ss.indexOf("error") < 0) {
					info = JSON.parseObject(ss, UserInfo.class);
					u =userService.selectByUserVo(info.getOpenid());
				}else {
					throw new Exception("出错了!");
				}
				if(StringUtils.isBlank(eventKey)){
						if (u == null) {
							User record = copyUser(info, eventKey);
							userService.insertUser(record);
							message = MessageUtil.initText(map.get("ToUserName"), map.get("FromUserName"), "欢迎关注");
							String btn = WeiXinUtils
									.initViewUserMenu(doctorUrl, shopUrl);
							WeiXinUtils.createMenu(accessToken, btn);
						}else {
							if("医生".equals(u.getRoleName())){
								message = MessageUtil.initText(map.get("ToUserName"), map.get("FromUserName"), "你好医生！");
								String btn = WeiXinUtils
										.initViewDoctorMenu(doctorUrl, shopUrl);
								WeiXinUtils.createMenu(accessToken, btn);
							}else if("销售员".equals(u.getRoleName())){
								message = MessageUtil.initText(map.get("ToUserName"), map.get("FromUserName"), "销售员");
								String btn = WeiXinUtils
										.initViewSalemanMenu(doctorUrl, shopUrl);
								WeiXinUtils.createMenu(accessToken, btn);
							}else if("店员".equals(u.getRoleName())){
								message = MessageUtil.initText(map.get("ToUserName"), map.get("FromUserName"), "你好店员！");
								String btn = WeiXinUtils
										.initViewDianyuanMenu(doctorUrl, shopUrl);
								WeiXinUtils.createMenu(accessToken, btn);
							}else{
								message = MessageUtil.initText(map.get("ToUserName"), map.get("FromUserName"), "欢迎关注");
								String btn = WeiXinUtils
									.initViewUserMenu(doctorUrl, shopUrl);
								WeiXinUtils.createMenu(accessToken, btn);
							}
						}
				}else{
					if(u==null){
						User record = copyUser(info, eventKey);
						userService.insertUser(record);
					}else{
						u.setRemark(key.substring(8));
						userService.updateUser(u);
					}
					message = MessageUtil.initText(map.get("ToUserName"), map.get("FromUserName"), "欢迎关注");
					String btn = WeiXinUtils
							.initViewUserMenu(doctorUrl, shopUrl);
					WeiXinUtils.createMenu(accessToken, btn);
				}
		
			}else if(MessageUtil.MESSAGE_CLICK.equals(eventType)){
				List<MyMessage> list =messageService.selectByState();
				if(list!=null&&list.size()>0){
					MyMessage msg=list.get(0);
					msg.setMessagePic(server_name+"/"+msg.getMessagePic());
					message =MessageUtil.initNewsMessage(map.get("ToUserName"), map.get("FromUserName"),msg);
				}
			}
		}
		return message;
	}

	private User copyUser(UserInfo info, String key) {
		User record = new User();
		record.setPicUrl(info.getHeadimgurl());
		record.setUsername("weixin");
		if (StringUtils.isNotBlank(key)) {
			log.info("key:" + key);
			record.setRemark(key.substring(8));
		}
		record.setWeName(info.getNickname());
		record.setName(info.getOpenid());
		record.setState(1);
		return record;
	}

	/**
	 * 生产带参数的二维码
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/admin/vCode")
	@ResponseBody
	public String creatCode(String id,HttpServletRequest request) {
		String rs = "error";
		if (StringUtils.isNotBlank(id)) {
			User u = userService.selectById(id);
			String accessToken="";
			AccessToken access=userService.selectToken();
			if(access==null||StringUtils.isBlank(access.getAccessToken())){
				rs =HttpClientUtil.getAccessToken(appId, appSecret);
				if(rs.indexOf("error") < 0){
					AccessToken token =JSON.parseObject(rs, AccessToken.class);
					accessToken =token.getAccessToken();
					token.setCreateTime(new Date());
					userService.insertToken(token);
				}
			}else if(CommonUtis.isDisable(access)){
				rs =HttpClientUtil.getAccessToken(appId, appSecret);
				if(rs.indexOf("error") < 0){
					AccessToken token =JSON.parseObject(rs, AccessToken.class);
					token.setId(access.getId());
					token.setCreateTime(new Date());
					userService.updateToken(token);
					accessToken =token.getAccessToken();
				}
			}else{
				accessToken=access.getAccessToken();
			}
			if (u != null && "医生".equals(u.getRoleName())) {
				String data = WeiXinUtils.createForeverStrTicket(accessToken, id);
				UnicodeResult result = JSON.parseObject(data, UnicodeResult.class);
				rs = result.getTicket();
				String pic ="https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket="+rs;
				Doctor d =new Doctor();
				d.setId(id);
				d.setDoctorWename(u.getWeName());
				d.setDoctorName(u.getRealName());
				d.setDoctorTelephone(u.getTelephone());
				d.setDoctorSecond(pic);
				try {
					doctorService.insertPihao(d);
				} catch (Exception e) {
					e.printStackTrace();
					rs="error";
				}
			}
		}
		
		return rs;
	}
	/**
	 * 去到商城登录
	 * @param code
	 * @param state
	 * @param res
	 * @return
	 */
	@RequestMapping("/phone/test")
	public String userAuthor(String code,String state,HttpServletRequest res){
		String ss =WeiXinUtils.getWebAuthorToken(appId,appSecret,code);
		String result ="redirect:/phone/shop";
		log.info("userAuthorInfo:"+ss);
		WebAuthorToken info =JSON.parseObject(ss, WebAuthorToken.class);
		User u =userService.selectByOpenId(info.getOpenid());
		res.getSession().setAttribute("u", u);
		return result;
	}
	/**
	 * 去到商城登录
	 * @param code
	 * @param state
	 * @param res
	 * @return
	 */
	@RequestMapping("/phone/center")
	public String userCenter(String code,String state,HttpServletRequest res){
		String ss =WeiXinUtils.getWebAuthorToken(appId,appSecret,code);
		String result ="redirect:/phone/userInfo";
		log.info("userAuthorInfo:"+ss);
		WebAuthorToken info =JSON.parseObject(ss, WebAuthorToken.class);
		User u =userService.selectByOpenId(info.getOpenid());
		res.getSession().setAttribute("u", u);
		if(u!=null&&"医生".equals(u.getRoleName())){
			result="redirect:/phone/doctor";
		}else if(u!=null&&"销售员".equals(u.getRoleName())){
			result="redirect:/phone/saleman";
		}else if("店员".equals(u.getRoleName())){
			result="redirect:/phone/dianyuan";
		}
		return result;
	}
}
